package cn.caplike.demo.kafka.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

/**
 * 手动提交 Offset
 */
public class ConsumerManuallyCommitOffsetAsync {

    public static void main(String[] args) {
        // 配置
        final Properties properties = getProperties();

        // 创建一个消费者
        try (final KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties)) {
            //noinspection ArraysAsListWithZeroOrOneArgument
            consumer.subscribe(Arrays.asList("first")); // 订阅主题

            // 消费数据
            //noinspection InfiniteLoopStatement
            while (true) {
                final ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
                for (ConsumerRecord<String, String> record : records) {
                    System.out.println("Consumer received: " + record);
                }

                // 手动提交
                consumer.commitAsync();
            }
        }
    }

    private static Properties getProperties() {
        final Properties properties = new Properties();

        // 连接
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "big-data-1:9092,big-data-2:9092,big-data-3:9092");
        // 反序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        // 配置消费者组 ID
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "A consumer");

        // 手动提交
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

        return properties;
    }
}
